import {UPDATE_AUTHORITY_INFO,DELETE_AUTHORITY_INFO} from "./types";

import {LoginPostAPI} from "@/api/auth";

// 配合localStorage实现登录相关的数据的长时间存储

export default {
    // 每次页面打开时 先获取是否存在用户信息 => 更新到state
    getAuthorityInfo({commit}){
        var str = localStorage.getItem("authorityInfo");
        if(str){
            var data = JSON.parse(str);
            commit(UPDATE_AUTHORITY_INFO,data);
            return data;
        }
        return "";
    },
    // 登录并存储用户信息 data = {adminname,rold,token}
    loginAndUpdateAuthority({commit},payload){
        // payload  登录的用户名和密码
        return LoginPostAPI(payload).then(res=>{
            var {data} = res;  // {code,message,data}
            commit(UPDATE_AUTHORITY_INFO,data);
            localStorage.setItem("authorityInfo",JSON.stringify(data))
        })
    },

    // 退出登录  -> state要初始化为原本的数据,删除localStorage
    exitLoginStatus({commit}){
        commit(DELETE_AUTHORITY_INFO);
        localStorage.removeItem("authorityInfo")
    }
}